import sys
import random
import string
import itertools
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                           QHBoxLayout, QPushButton, QLabel, QSpinBox, 
                           QTextEdit, QFileDialog, QProgressBar, QMessageBox,
                           QCheckBox, QGroupBox, QStyle, QStyleFactory)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QFont

class PasswordGenerator(QThread):
    progress_signal = pyqtSignal(int, str)
    finished_signal = pyqtSignal(list)
    
    def __init__(self, config):
        super().__init__()
        self.config = config
        
    def generate_8digit_passwords(self, count):
        """生成8位数字密码"""
        passwords = set()
        while len(passwords) < count:
            pwd = ''.join(random.choices(string.digits, k=8))
            passwords.add(pwd)
            if len(passwords) % 10 == 0:
                self.progress_signal.emit(len(passwords), pwd)
        return passwords

    def generate_8char_passwords(self, count):
        """生成8位大小写字母密码"""
        passwords = set()
        while len(passwords) < count:
            pwd = ''.join(random.choices(string.ascii_letters, k=8))
            passwords.add(pwd)
            if len(passwords) % 10 == 0:
                self.progress_signal.emit(len(passwords), pwd)
        return passwords

    def generate_common_passwords(self):
        """生成常见密码组合"""
        common = [
            "12345678", "88888888", "00000000", "11111111",
            "1234567890", "66666666", "18967482169", "123456789",
            "00000000", "87654321", "66668888", "11223344",
             "147258369 ", "11111111",
        ]
        return set(common)

    def generate_isp_passwords(self):
        """生成运营商风格密码"""
        passwords = set()
        prefixes = ['CMCC', 'CHINA', 'MOBILE', 'UNICOM', 'TELECOM', 'CU', 'CT', 'CM']
        
        # 生成前缀+数字组合
        for prefix in prefixes:
            if len(prefix) <= 4:
                remain_length = 8 - len(prefix)
                for i in range(min(100, 10 ** remain_length)):  # 限制数量
                    num = str(i).zfill(remain_length)
                    passwords.add(f"{prefix}{num}")
                    passwords.add(f"{prefix.lower()}{num}")
                    if len(passwords) % 10 == 0:
                        self.progress_signal.emit(len(passwords), f"{prefix}{num}")

        # 生成特定模式
        patterns = ['CMCC####', 'CUCC####', 'CTCC####', 'CU######', 'CT######', 'CM######']
        for pattern in patterns:
            digit_positions = [i for i, char in enumerate(pattern) if char == '#']
            letters_part = ''.join(c for c in pattern if c != '#')
            
            for nums in itertools.islice(itertools.product('0123456789', repeat=len(digit_positions)), 100):
                pwd = list(letters_part + '0' * len(digit_positions))
                for pos, num in zip(digit_positions, nums):
                    pwd[pos] = num
                passwords.add(''.join(pwd))
                if len(passwords) % 10 == 0:
                    self.progress_signal.emit(len(passwords), ''.join(pwd))

        return passwords

    def run(self):
        all_passwords = set()
        
        if self.config['common']:
            common = self.generate_common_passwords()
            all_passwords.update(common)
            self.progress_signal.emit(len(all_passwords), "常见密码生成完成")

        if self.config['digits']:
            digits = self.generate_8digit_passwords(self.config['digit_count'])
            all_passwords.update(digits)
            self.progress_signal.emit(len(all_passwords), "数字密码生成完成")

        if self.config['chars']:
            chars = self.generate_8char_passwords(self.config['char_count'])
            all_passwords.update(chars)
            self.progress_signal.emit(len(all_passwords), "字母密码生成完成")

        if self.config['isp']:
            isp = self.generate_isp_passwords()
            all_passwords.update(isp)
            self.progress_signal.emit(len(all_passwords), "运营商密码生成完成")

        self.finished_signal.emit(sorted(list(all_passwords)))

class PasswordGeneratorGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('WiFi密码字典生成器')
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QPushButton {
                background-color: #0078d4;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #106ebe;
            }
            QPushButton:disabled {
                background-color: #cccccc;
            }
            QGroupBox {
                border: 1px solid #cccccc;
                border-radius: 4px;
                margin-top: 10px;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px 0 3px;
            }
            QSpinBox {
                padding: 5px;
                border: 1px solid #cccccc;
                border-radius: 4px;
            }
        """)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setSpacing(20)
        layout.setContentsMargins(20, 20, 20, 20)

        # 密码类型选择
        type_group = QGroupBox("密码类型")
        type_layout = QVBoxLayout()
        
        # 常见密码选项
        self.common_check = QCheckBox("包含常见密码")
        self.common_check.setChecked(True)
        type_layout.addWidget(self.common_check)

        # 数字密码选项
        digit_layout = QHBoxLayout()
        self.digit_check = QCheckBox("生成8位数字密码")
        self.digit_check.setChecked(True)
        self.digit_count = QSpinBox()
        self.digit_count.setRange(100, 10000)
        self.digit_count.setValue(1000)
        digit_layout.addWidget(self.digit_check)
        digit_layout.addWidget(self.digit_count)
        type_layout.addLayout(digit_layout)

        # 字母密码选项
        char_layout = QHBoxLayout()
        self.char_check = QCheckBox("生成8位字母密码")
        self.char_check.setChecked(True)
        self.char_count = QSpinBox()
        self.char_count.setRange(100, 10000)
        self.char_count.setValue(1000)
        char_layout.addWidget(self.char_check)
        char_layout.addWidget(self.char_count)
        type_layout.addLayout(char_layout)

        # 运营商密码选项
        self.isp_check = QCheckBox("包含运营商特征密码")
        self.isp_check.setChecked(True)
        type_layout.addWidget(self.isp_check)

        type_group.setLayout(type_layout)
        layout.addWidget(type_group)

        # 进度显示
        self.progress_bar = QProgressBar()
        layout.addWidget(self.progress_bar)

        # 状态显示
        self.status_text = QTextEdit()
        self.status_text.setReadOnly(True)
        self.status_text.setMinimumHeight(200)
        layout.addWidget(self.status_text)

        # 控制按钮
        button_layout = QHBoxLayout()
        self.generate_btn = QPushButton('生成密码字典')
        self.generate_btn.clicked.connect(self.start_generation)
        self.save_btn = QPushButton('保存密码字典')
        self.save_btn.clicked.connect(self.save_passwords)
        self.save_btn.setEnabled(False)
        button_layout.addWidget(self.generate_btn)
        button_layout.addWidget(self.save_btn)
        layout.addLayout(button_layout)

        # 设置窗口大小和位置
        self.setGeometry(100, 100, 600, 500)
        
        self.passwords = []  # 存储生成的密码

    def start_generation(self):
        if not any([self.common_check.isChecked(), 
                   self.digit_check.isChecked(),
                   self.char_check.isChecked(),
                   self.isp_check.isChecked()]):
            QMessageBox.warning(self, "警告", "请至少选择一种密码类型")
            return

        self.status_text.clear()
        self.progress_bar.setValue(0)
        self.generate_btn.setEnabled(False)
        self.save_btn.setEnabled(False)

        config = {
            'common': self.common_check.isChecked(),
            'digits': self.digit_check.isChecked(),
            'chars': self.char_check.isChecked(),
            'isp': self.isp_check.isChecked(),
            'digit_count': self.digit_count.value(),
            'char_count': self.char_count.value()
        }

        self.generator = PasswordGenerator(config)
        self.generator.progress_signal.connect(self.update_progress)
        self.generator.finished_signal.connect(self.generation_finished)
        self.generator.start()

    def update_progress(self, count, current):
        self.status_text.append(f"已生成: {current}")
        self.status_text.verticalScrollBar().setValue(
            self.status_text.verticalScrollBar().maximum()
        )
        # 更新进度条（假设最大10000个密码）
        self.progress_bar.setValue(min(100, int(count / 100)))

    def generation_finished(self, passwords):
        self.passwords = passwords
        self.status_text.append(f"\n密码生成完成！共生成 {len(passwords)} 个密码")
        self.generate_btn.setEnabled(True)
        self.save_btn.setEnabled(True)
        self.progress_bar.setValue(100)

    def save_passwords(self):
        if not self.passwords:
            QMessageBox.warning(self, "警告", "没有可保存的密码")
            return

        file_name, _ = QFileDialog.getSaveFileName(
            self, "保存密码字典", "wifi_password_dict.txt", "文本文件 (*.txt)")
        
        if file_name:
            try:
                with open(file_name, 'w', encoding='utf-8') as f:
                    f.write('\n'.join(self.passwords))
                QMessageBox.information(self, "成功", f"密码字典已保存到: {file_name}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存文件时出错: {str(e)}")

def main():
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create('Fusion'))
    window = PasswordGeneratorGUI()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main() 